package com.openx.xoj.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.openx.xoj.mapper.QuestionFavourMapper;
import com.openx.xoj.mapper.QuestionMapper;
import com.openx.xoj.model.entity.Question;
import com.openx.xoj.model.entity.QuestionFavour;
import com.openx.xoj.service.MistakeQuestionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class MistakeQuestionServiceImpl implements MistakeQuestionService {

    @Autowired
    private QuestionFavourMapper questionFavourMapper;

    @Autowired
    private QuestionMapper questionMapper;

    @Override
    public List<Question> recommendQuestions(Long userId) {
        // 1. 获取用户收藏的题目ID
        QueryWrapper<QuestionFavour> wrapper = new QueryWrapper<>();
        wrapper.eq("userId", userId);
        List<Long> questionIds = questionFavourMapper.selectList(wrapper)
                .stream().map(QuestionFavour::getQuestionId)
                .collect(Collectors.toList());

        System.out.println("收藏的题目ID：" + questionIds);

        if (questionIds.isEmpty()) {
            return Collections.emptyList();
        }

        // 2. 获取这些题目的详细信息
        List<Question> questions = questionMapper.selectBatchIds(questionIds);
        System.out.println("收藏的题目详细信息：" + questions);

        // 3. 查找每个题目的相似题目
        List<Question> similarQuestions = new ArrayList<>();
        for (Question question : questions) {
            QueryWrapper<Question> tagWrapper = new QueryWrapper<>();
            tagWrapper.ne("id", question.getId())
                    .like("tags", question.getTags().split(",")[0]); // 这里只匹配第一个标签
            Question similarQuestion = questionMapper.selectOne(tagWrapper);
            if (similarQuestion != null) {
                similarQuestions.add(similarQuestion);
            }
        }

        System.out.println("推荐的相似题目：" + similarQuestions);

        return similarQuestions;
    }
}
